package dao

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"html"
	"html/template"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

//Json Return
type Return struct {
	Error   int         `json:"error"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

//ToJsonByte
func (r *Return) ToJsonByte() []byte {
	str, err := json.MarshalIndent(r, "", "\t")
	if err != nil {
		return []byte{}
	}
	return str
}

//ResponseJson
func (r *Return) ResponseJson(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	str, err := json.MarshalIndent(r, "", "\t")
	if err != nil {
		return err
	}

	_, err2 := w.Write(str)
	return err2
}

func GetCurrentUrl(r *http.Request) (str string) {
	scheme := "http://"
	if r.TLS != nil {
		scheme = "https://"
	}
	str = strings.Join([]string{scheme, r.Host, r.RequestURI}, "")
	return
}

func ShowErrorPage(notice string, httpCode int, w http.ResponseWriter) {
	w.WriteHeader(httpCode) //HTTP状态码
	w.Write([]byte(notice))
}

/**
datetime格式时间转时间戳
*/
func DatetimeToTimeZone(timeString string) (timeZone int64) {
	tm2, err := time.Parse(TimeLayout, timeString)
	if err != nil {
		return 0
	}
	timeZone = tm2.Unix()
	return
}

//template.FuncMap
/**
ShowMonthDay
*/
func ShowMonthDay(dataTime string) string {
	return dataTime[5:7] + "." + dataTime[8:10]
}

/**
GetYear
*/
func GetYear(dataTime string) string {
	return dataTime[:4]
}

//获取配置的value
func ShowSiteCFG(key string) template.HTML {
	if D, exists := Cache[key]; exists {
		if val, ok := D.(SiteOPT); ok {
			return template.HTML(html.UnescapeString(val.Value))
		}
	}
	return template.HTML("")
}

//转义
func Unescaped(x string) interface{} {
	return template.HTML(x)
}

//获取访问者IP
func GetCurrentIp(r *http.Request) (ip string) {

	ip = r.Header.Get("X-Real-IP")
	if ip == "" {
		ip = r.RemoteAddr
		ip = ip[0:strings.LastIndex(ip, ":")]
	}

	return
}

//GetCurrentUA
func GetCurrentUA(r *http.Request) (ua string) {
	return r.Header.Get("User-Agent")
}

// 生成32位MD5
func Md5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

//生成随机字符串
func GetRandomString(length uint) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	var i uint
	for i = 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

/**
数据分页
@param int     pagenumber  当前页
@param int     pagecount   总页数
@param string  baseUrl     链接地址(需要带上?)
*/
func Pager(pagenumber, pagecount int, baseUrl string) template.HTML {
	if pagecount <= 0 {
		return template.HTML("")
	}

	renderButton := func(buttonLabel string, pagenumber, pagecount int, baseUrl string) (str string) {
		className := ""
		destPage := 1

		switch buttonLabel {
		case "首页":
			destPage = 1
		case "上一页":
			destPage = pagenumber - 1
		case "下一页":
			destPage = pagenumber + 1
		case "末页":
			destPage = pagecount
		}

		if buttonLabel == "首页" || buttonLabel == "上一页" {
			if pagenumber <= 1 {
				className = " pgEmpty"
			}
		} else {
			if pagenumber >= pagecount {
				className = " pgEmpty"
			}
		}

		str = fmt.Sprintf("                <a class='pgNext%s' href='%s&page=%d'>%s</a>", className, baseUrl, destPage, buttonLabel)
		return
	}

	var htmlArr []string
	htmlArr = append(htmlArr, `<div id="pager">`)
	if pagenumber > 1 {
		if pagenumber > 2 {
			htmlArr = append(htmlArr, renderButton("首页", pagenumber, pagecount, baseUrl))
		}
		htmlArr = append(htmlArr, renderButton("上一页", pagenumber, pagecount, baseUrl))
	}

	var startPoint = 1
	var endPoint = 5

	if pagenumber >= 5 {
		startPoint = pagenumber - 2
		endPoint = pagenumber + 2
	}

	if endPoint > pagecount {
		startPoint = pagecount - 4
		endPoint = pagecount
	}

	if startPoint < 1 {
		startPoint = 1
	}

	for page := startPoint; page <= endPoint; page++ {
		if page == pagenumber {
			htmlArr = append(htmlArr, fmt.Sprintf(`                <a class="page-number pgCurrent" href="%s&page=%d">%d</a>`, baseUrl, page, page))
		} else {
			htmlArr = append(htmlArr, fmt.Sprintf(`                <a class="page-number" href="%s&page=%d">%d</a>`, baseUrl, page, page))
		}
	}

	if pagenumber < pagecount {
		htmlArr = append(htmlArr, renderButton("下一页", pagenumber, pagecount, baseUrl))
		if (pagecount - pagenumber) > 1 {
			htmlArr = append(htmlArr, renderButton("末页", pagenumber, pagecount, baseUrl))
		}
	}

	htmlArr = append(htmlArr, `            </div>`)
	return template.HTML(strings.Join(htmlArr, fmt.Sprintf("\n")))
}
